import React, { PureComponent } from 'react';
import { Layout, Menu, Icon } from 'antd';
import { withRouter } from 'react-router-dom'
const { Sider } = Layout;
const { SubMenu } = Menu;
@withRouter
export default class NavLeft extends PureComponent {
	state = {
		collapsed: false,
	};

	shouldComponentUpdate (nextProps, nextState) {
		if (nextProps.collapsed !== nextState.collapsed) {
			this.state.collapsed = nextProps.collapsed
			return true
		}
		return false
	}

	handlerJump = (path) => {
		if (this.props.location.pathname === path) return
		this.props.history.push(path)
	}

	renderMenu = (tree) => {
		return tree.map(item => {
			if (item.children && item.children.length > 0) {
				return <SubMenu key={item.path} title={
					<span>
						<Icon type={item.icon} />
						<span>{item.name}</span>
					</span>
				}>
					{this.renderMenu(item.children, item)}
				</SubMenu>
			} else {
				return <Menu.Item key={item.path} onClick={() => { this.handlerJump(item.path) }}>
					<Icon type={item.icon} />
					<span>{item.name}</span>
				</Menu.Item>
			}
		})
	}

	getOpenKeys = () => {
		let defaultOpenKeys = []
		let pathArr = this.props.location.pathname.split('/')
		pathArr.shift()
		pathArr.forEach((item, index) => {
			item = '/' + item
			if (index != pathArr.length - 1) {
				let tempPath = defaultOpenKeys[index - 1]
				tempPath && (item = tempPath + item)
				defaultOpenKeys.push(item)
			}
		})
		let selectedKeys = this.props.location.pathname
		return {
			defaultOpenKeys,
			defaultSelectedKeys: [selectedKeys === '/' ? '/home' : selectedKeys]
		}
	}

	render () {
		const { defaultOpenKeys, defaultSelectedKeys } = this.getOpenKeys();
		return (
			<Sider trigger={null} collapsible collapsed={this.props.collapsed}>
				<div className="admin-layout-logo"></div>
				<h2 className="admin-layout-title">核心系统</h2>
				<Menu theme="dark" mode="inline" defaultOpenKeys={defaultOpenKeys} defaultSelectedKeys={defaultSelectedKeys} >
					{
						this.renderMenu(this.props.menu)
					}
				</Menu>
			</Sider>
		);
	}
}
